import { useEffect, useState } from 'react';
import { Empty, Button, Space, Card, Image, Toast, Checkbox } from '@nutui/nutui-react';
import { useSelector } from 'react-redux';
import { api } from '@/api/api';
import { formatPrice } from '@/utils/formatPrice';
import noData from '@/assets/images/no-data.png';
import './index.less';

const CartView = () => {
    const userInfo = useSelector(state => state.user.userInfo);
    const shopId = useSelector(state => state.shop.shopId);

    const [cartList, setCartList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [updating, setUpdating] = useState({});
    const [selectedItems, setSelectedItems] = useState([]);
    const [isEditMode, setIsEditMode] = useState(false);
    const [deleteItems, setDeleteItems] = useState([]);
    const [creatingOrder, setCreatingOrder] = useState(false);

    // 获取购物车列表
    const fetchCartList = async () => {
        if (!userInfo || !userInfo.userId) {
            return;
        }

        try {
            setLoading(true);
            const response = await api.getCartList({ userId: userInfo.userId, shopId  });
            
            if (response.code === 200) {
                setCartList(response.data || []);
                // 初始化选中状态
                const selected = response.data?.filter(item => item.isSelected === 1).map(item => item.id) || [];
                setSelectedItems(selected);
            }
        } catch (error) {
            Toast.show('获取购物车列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 更新商品数量
    const handleUpdateQuantity = async (cartItem, newQuantity) => {
        if (!userInfo || !userInfo.userId) {
            Toast.show('请先登录');
            return;
        }

        const itemId = cartItem.id;
        setUpdating(prev => ({ ...prev, [itemId]: true }));

        try {
            const response = await api.updateCart({
                id: cartItem.id,
                quantity: newQuantity
            });

            if (response.code === 200) {
                // 更新本地状态
                setCartList(prev => 
                    prev.map(item => 
                        item.id === cartItem.id 
                            ? { ...item, quantity: newQuantity, countPrice: newQuantity * item.price }
                            : item
                    )
                );
            } else {
                Toast.show('更新失败，请重试');
            }
        } catch (error) {
            console.error('更新购物车失败:', error);
            Toast.show('更新失败，请重试');
        } finally {
            setUpdating(prev => ({ ...prev, [itemId]: false }));
        }
    };

    // 批量删除商品
    const handleBatchDelete = async () => {
        if (!userInfo || !userInfo.userId) {
            Toast.show('请先登录');
            return;
        }

        if (deleteItems.length === 0) {
            Toast.show('请选择要删除的商品');
            return;
        }

        try {
            const response = await api.deleteShoppingCart({
                ids: deleteItems.join(',')
            });

            if (response.code === 200) {
                setCartList(prev => prev.filter(item => !deleteItems.includes(item.id)));
                setSelectedItems(prev => prev.filter(id => !deleteItems.includes(id)));
                setDeleteItems([]);
                Toast.show(`已删除${deleteItems.length}件商品`);
            } else {
                Toast.show('删除失败，请重试');
            }
        } catch (error) {
            console.error('批量删除失败:', error);
            Toast.show('删除失败，请重试');
        }
    };

    // 切换编辑模式
    const toggleEditMode = () => {
        setIsEditMode(!isEditMode);
        if (isEditMode) {
            setDeleteItems([]);
        }
    };

    // 切换删除选择
    const handleToggleDelete = (itemId) => {
        setDeleteItems(prev => {
            if (prev.includes(itemId)) {
                return prev.filter(id => id !== itemId);
            } else {
                return [...prev, itemId];
            }
        });
    };

    // 全选删除
    const handleSelectAllDelete = () => {
        if (deleteItems.length === cartList.length) {
            setDeleteItems([]);
        } else {
            setDeleteItems(cartList.map(item => item.id));
        }
    };

    // 切换单个商品选中状态
    const handleToggleSelect = async (itemId) => {
        if (!userInfo || !userInfo.userId) {
            Toast.show('请先登录');
            return;
        }

        const isCurrentlySelected = selectedItems.includes(itemId);
        const newSelectedState = isCurrentlySelected ? 0 : 1;

        try {
            const response = await api.updateShoppingCartIsSelected({
                ids: itemId.toString(),
                isSelected: newSelectedState.toString()
            });

            if (response.code === 200) {
                // 更新本地状态
                setSelectedItems(prev => {
                    if (isCurrentlySelected) {
                        return prev.filter(id => id !== itemId);
                    } else {
                        return [...prev, itemId];
                    }
                });

                // 更新购物车列表中的isSelected状态
                setCartList(prev => 
                    prev.map(item => 
                        item.id === itemId 
                            ? { ...item, isSelected: newSelectedState }
                            : item
                    )
                );
            } else {
                Toast.show('更新选中状态失败');
            }
        } catch (error) {
            console.error('更新选中状态失败:', error);
            Toast.show('更新选中状态失败');
        }
    };

    // 全选/取消全选
    const handleSelectAll = async () => {
        if (!userInfo || !userInfo.userId) {
            Toast.show('请先登录');
            return;
        }

        const isSelectAll = selectedItems.length === cartList.length;
        const newSelectedState = isSelectAll ? 0 : 1;
        const allIds = cartList.map(item => item.id);

        try {
            const response = await api.updateShoppingCartIsSelected({
                ids: allIds.join(','),
                isSelected: newSelectedState.toString()
            });

            if (response.code === 200) {
                if (isSelectAll) {
                    setSelectedItems([]);
                } else {
                    setSelectedItems(allIds);
                }

                // 更新购物车列表中的isSelected状态
                setCartList(prev => 
                    prev.map(item => ({ ...item, isSelected: newSelectedState }))
                );
            } else {
                Toast.show('更新选中状态失败');
            }
        } catch (error) {
            console.error('更新选中状态失败:', error);
            Toast.show('更新选中状态失败');
        }
    };

    const handleCreateOrder = async () => {
        if (!userInfo || !userInfo.userId) {
            Toast.show('请先登录');
            return;
        }

        if (selectedItems.length === 0) {
            Toast.show('请选择要结算的商品');
            return;
        }

        try {
            setCreatingOrder(true);
            
            const currentShopId = shopId || localStorage.getItem("shop_id");
            const response = await api.createOrder({
                userId: userInfo.userId,
                shoppingCartId: selectedItems,
                shopId: currentShopId,
                remark: "加急发货"
            });
            
            if (response.code === 200) {
                if (selectedTotalPrice === 0) {
                    Toast.show('订单创建成功！');
                    setSelectedItems([]);
                    fetchCartList();
                } else {
                    const prepayId = response.data.prepay_id;
                    const res = await api.getPaySign(prepayId);
                    const payConfig = res.data;
                    window.WeixinJSBridge.invoke('getBrandWCPayRequest', {
                        "appId": payConfig.appId,  
                        "timeStamp": payConfig.timestamp,
                        "nonceStr": payConfig.nonceStr, 
                        "package": `prepay_id=${payConfig.prepayId}`,
                        "signType": "RSA",   
                        "paySign": payConfig.paySign,
                    },(res)=>{
                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                            Toast.show('支付成功！');
                            setSelectedItems([]);
                            fetchCartList();
                        }
                    });
                }
            } else {
                Toast.show('订单创建失败，请重试');
            }
        } catch (error) {
            console.error('创建订单失败:', error);
            Toast.show('订单创建失败，请重试');
        } finally {
            setCreatingOrder(false);
        }
    };

    // 调用微信支付
    // const callWechatPay = async (prepayId) => {
    //     try {
    //         // 获取微信支付配置
    //         const configResponse = await api.getWechatConfig({
    //             shopId: '',
    //             // url: window.location.href
    //         });
            
    //         if (configResponse.code === 200) {
    //             const config = configResponse.data;
                
    //             // 配置微信JSAPI
    //             if (window.wx) {
    //                 window.wx.config({
    //                     debug: false,
    //                     appId: config.appId,
    //                     timestamp: config.timestamp,
    //                     nonceStr: config.nonceStr,
    //                     signature: config.signature,
    //                     jsApiList: ['chooseWXPay']
    //                 });
                    
    //                 window.wx.ready(() => {
    //                     // 调用微信支付
    //                     window.wx.chooseWXPay({
    //                         timestamp: config.timestamp,
    //                         nonceStr: config.nonceStr,
    //                         package: `prepay_id=${prepayId}`,
    //                         signType: 'MD5',
    //                         paySign: config.paySign,
    //                         success: (res) => {
    //                             Toast.show('支付成功');
    //                         },
    //                         fail: (res) => {
    //                             Toast.show('支付失败');
    //                         },
    //                         cancel: (res) => {
    //                             Toast.show('支付取消');
    //                         }
    //                     });
    //                 });
                    
    //                 window.wx.error((res) => {
    //                     Toast.show('微信支付配置失败');
    //                 });
    //             } else {
    //                 Toast.show('微信支付环境未准备好');
    //             }
    //         } else {
    //             Toast.show('获取微信支付配置失败');
    //         }
    //     } catch (error) {
    //         Toast.show('微信支付调用失败');
    //     }
    // };

    useEffect(() => {
        fetchCartList();
    }, [userInfo]);

    // 计算选中商品的总价
    const selectedTotalPrice = cartList
        .filter(item => selectedItems.includes(item.id))
        .reduce((sum, item) => sum + item.countPrice, 0);

    return (
        <div className="cart-container">
            {loading ? (
                <div className="loading-container">加载中...</div>
            ) : cartList.length > 0 ? (
                <>
                    <div className="cart-header">
                        <div className="cart-title">
                            购物车({cartList.length})
                        </div>
                        <div 
                            className="edit-button"
                            onClick={toggleEditMode}
                        >
                            {isEditMode ? '完成' : '编辑'}
                        </div>
                    </div>

                    {/* 商品列表 */}
                    <div className="cart-list">
                        {cartList.map((item, index) => (
                            <div key={index} className="cart-item">
                                <div className="checkbox-container">
                                    {isEditMode ? (
                                        <Checkbox
                                            checked={deleteItems.includes(item.id)}
                                            onChange={() => handleToggleDelete(item.id)}
                                        />
                                    ) : (
                                        <Checkbox
                                            checked={selectedItems.includes(item.id)}
                                            onChange={() => handleToggleSelect(item.id)}
                                        />
                                    )}
                                </div>
                                
                                <div className="image-container">
                                    <Image
                                        src={item.productImage || 'https://via.placeholder.com/80x80'}
                                        alt={item.productName}
                                        width="80"
                                        height="80"
                                        className="product-image"
                                    />
                                </div>
                                
                                {/* 商品信息 */}
                                <div className="product-info">
                                    <div className="product-name">
                                        {item.productName}
                                    </div>
                                    
                                    <div className="product-details">
                                        {item.productName} X{item.quantity}
                                    </div>
                                    
                                    <div className="price-quantity-container">
                                        <div className="product-price">
                                            价格: {formatPrice(item.price)}
                                        </div>
                                        
                                        {!isEditMode && (
                                            <div className="quantity-controls">
                                                <Button
                                                    size="small"
                                                    type="default"
                                                    onClick={() => handleUpdateQuantity(item, Math.max(1, item.quantity - 1))}
                                                    disabled={updating[item.id] || item.quantity <= 1}
                                                    className="quantity-button"
                                                >
                                                    −
                                                </Button>
                                                <span className="quantity-display">
                                                    {item.quantity}
                                                </span>
                                                <Button
                                                    size="small"
                                                    type="default"
                                                    onClick={() => handleUpdateQuantity(item, item.quantity + 1)}
                                                    disabled={updating[item.id] || item.quantity >= 99}
                                                    className="quantity-button"
                                                >
                                                    +
                                                </Button>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                    
                    {/* 底部操作区域 */}
                    <div className="bottom-actions">
                        {isEditMode ? (
                            // 编辑模式底部
                            <>
                                <div className="select-all-container">
                                    <Checkbox
                                        checked={deleteItems.length === cartList.length && cartList.length > 0}
                                        onChange={handleSelectAllDelete}
                                        className="select-all-checkbox"
                                    />
                                    <span className="select-all-text">全选</span>
                                </div>
                                
                                <Button 
                                    type="danger" 
                                    size="large"
                                    disabled={deleteItems.length === 0}
                                    onClick={handleBatchDelete}
                                    className="delete-button"
                                >
                                    删除({deleteItems.length})
                                </Button>
                            </>
                        ) : (
                            // 正常模式底部
                            <>
                                <div className="select-all-container">
                                    <Checkbox
                                        checked={selectedItems.length === cartList.length && cartList.length > 0}
                                        onChange={handleSelectAll}
                                        className="select-all-checkbox"
                                    />
                                    <span className="select-all-text">全选</span>
                                </div>
                                
                                <div className="checkout-container">
                                    <div className="price-info">
                                        <div className="price-label">
                                            价格: {formatPrice(selectedTotalPrice)}
                                        </div>
                                    </div>
                                    <Button 
                                        type="primary" 
                                        size="large"
                                        disabled={selectedItems.length === 0 || creatingOrder}
                                        onClick={handleCreateOrder}
                                        className="checkout-button"
                                        loading={creatingOrder}
                                    >
                                        {creatingOrder ? '创建订单中...' : '去结算'}
                                    </Button>
                                </div>
                            </>
                        )}
                    </div>
                </>
            ) : (
                <Empty
                    image={<img src={noData} alt="" />}
                    description="购物车为空"
                    actions={[{ text: '去下单' }]}
                    style={{ marginTop: '40px' }}
                />
            )}
        </div>
    );
};

export default CartView;
